/**
 * 状态管理组合式函数
 * 提供统一的状态获取和管理接口
 */
import { ref, computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useStateStore } from '@/stores/state'
import type { StateInfo, StateOption } from '@/types/state'

export interface UseStateManagerOptions {
  /** 模块类型 */
  moduleType: string
  /** 是否自动加载 */
  autoLoad?: boolean
  /** 是否只获取启用的状态 */
  enabledOnly?: boolean
  /** 是否只获取可见的状态 */
  visibleOnly?: boolean
}

export function useStateManager(options: UseStateManagerOptions) {
  const stateStore = useStateStore()
  const { states, loading, error } = storeToRefs(stateStore)
  
  const moduleType = ref(options.moduleType)
  const enabledOnly = ref(options.enabledOnly ?? false)
  const visibleOnly = ref(options.visibleOnly ?? true)
  
  // 当前模块的状态列表
  const moduleStates = computed(() => {
    const allStates = states.value[moduleType.value] || []
    
    let filteredStates = allStates
    
    if (enabledOnly.value) {
      filteredStates = filteredStates.filter(state => state.is_enabled)
    }
    
    if (visibleOnly.value) {
      filteredStates = filteredStates.filter(state => state.is_visible)
    }
    
    return filteredStates.sort((a, b) => a.sort_order - b.sort_order)
  })
  
  // 状态选项（用于下拉框）
  const stateOptions = computed((): StateOption[] => {
    return moduleStates.value.map(state => ({
      label: state.name,
      value: state.code,
      color: state.color,
      icon: state.icon,
      disabled: !state.is_enabled
    }))
  })
  
  // 默认状态
  const defaultState = computed(() => {
    return moduleStates.value.find(state => state.is_default) || 
           moduleStates.value.find(state => state.is_enabled) ||
           moduleStates.value[0]
  })
  
  // 根据代码获取状态
  const getStateByCode = (code: string): StateInfo | undefined => {
    return moduleStates.value.find(state => state.code === code)
  }
  
  // 根据名称获取状态
  const getStateByName = (name: string): StateInfo | undefined => {
    return moduleStates.value.find(state => state.name === name)
  }
  
  // 验证状态代码
  const validateStateCode = (code: string): boolean => {
    const state = getStateByCode(code)
    return state !== undefined && state.is_enabled
  }
  
  // 获取状态显示名称
  const getStateDisplayName = (code: string): string => {
    const state = getStateByCode(code)
    return state?.name || code
  }
  
  // 获取状态颜色
  const getStateColor = (code: string): string => {
    const state = getStateByCode(code)
    return state?.color || '#1890ff'
  }
  
  // 获取状态图标
  const getStateIcon = (code: string): string | undefined => {
    const state = getStateByCode(code)
    return state?.icon
  }
  
  // 加载状态数据
  const loadStates = async (forceRefresh = false) => {
    try {
      await stateStore.fetchModuleStates(moduleType.value, forceRefresh)
    } catch (err) {
      console.error(`Failed to load states for module ${moduleType.value}:`, err)
      throw err
    }
  }
  
  // 刷新状态数据
  const refreshStates = () => loadStates(true)
  
  // 切换模块类型
  const switchModule = async (newModuleType: string) => {
    moduleType.value = newModuleType
    await loadStates()
  }
  
  // 监听模块类型变化
  watch(moduleType, async (newModuleType) => {
    if (newModuleType && options.autoLoad !== false) {
      await loadStates()
    }
  }, { immediate: options.autoLoad !== false })
  
  return {
    // 响应式数据
    moduleType,
    enabledOnly,
    visibleOnly,
    loading: computed(() => loading.value),
    error: computed(() => error.value),
    
    // 计算属性
    moduleStates,
    stateOptions,
    defaultState,
    
    // 方法
    getStateByCode,
    getStateByName,
    validateStateCode,
    getStateDisplayName,
    getStateColor,
    getStateIcon,
    loadStates,
    refreshStates,
    switchModule
  }
}

/**
 * 多模块状态管理
 */
export function useMultiStateManager(moduleTypes: string[]) {
  const stateStore = useStateStore()
  const { states, loading, error } = storeToRefs(stateStore)
  
  // 加载多个模块的状态
  const loadAllStates = async (forceRefresh = false) => {
    try {
      await Promise.all(
        moduleTypes.map(moduleType => 
          stateStore.fetchModuleStates(moduleType, forceRefresh)
        )
      )
    } catch (err) {
      console.error('Failed to load states for modules:', moduleTypes, err)
      throw err
    }
  }
  
  // 获取所有模块的状态选项
  const getAllStateOptions = (): Record<string, StateOption[]> => {
    const result: Record<string, StateOption[]> = {}
    
    moduleTypes.forEach(moduleType => {
      const moduleStates = states.value[moduleType] || []
      result[moduleType] = moduleStates
        .filter(state => state.is_visible)
        .sort((a, b) => a.sort_order - b.sort_order)
        .map(state => ({
          label: state.name,
          value: state.code,
          color: state.color,
          icon: state.icon,
          disabled: !state.is_enabled
        }))
    })
    
    return result
  }
  
  // 批量验证状态代码
  const validateStateCodes = (codes: Record<string, string>): Record<string, boolean> => {
    const result: Record<string, boolean> = {}
    
    Object.entries(codes).forEach(([moduleType, code]) => {
      const moduleStates = states.value[moduleType] || []
      const state = moduleStates.find(s => s.code === code)
      result[moduleType] = state !== undefined && state.is_enabled
    })
    
    return result
  }
  
  return {
    loading: computed(() => loading.value),
    error: computed(() => error.value),
    states: computed(() => states.value),
    
    loadAllStates,
    getAllStateOptions,
    validateStateCodes
  }
}

/**
 * 状态转换管理
 */
export function useStateTransition(moduleType: string) {
  const { moduleStates, getStateByCode } = useStateManager({ moduleType })
  
  // 获取可转换的状态
  const getTransitionableStates = (currentStateCode: string): StateInfo[] => {
    // 这里可以根据业务规则定义状态转换逻辑
    // 目前返回所有启用的状态
    return moduleStates.value.filter(state => 
      state.is_enabled && state.code !== currentStateCode
    )
  }
  
  // 验证状态转换是否允许
  const canTransitionTo = (fromCode: string, toCode: string): boolean => {
    const fromState = getStateByCode(fromCode)
    const toState = getStateByCode(toCode)
    
    if (!fromState || !toState || !toState.is_enabled) {
      return false
    }
    
    // 这里可以添加更复杂的转换规则
    return true
  }
  
  return {
    moduleStates,
    getTransitionableStates,
    canTransitionTo
  }
}